<template>
  <div v-show="$route.name == 'material-out'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>原料仓出仓明细</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <div style="margin-bottom: 20px;">原料仓出仓明细</div>
      <el-row class="query" v-if="groupid === 0">
        <el-col :span="24">
          <el-date-picker
            v-model="exportSearch.exportTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
          <el-select v-model="exportSearch.base" popper-class="dropdownbox" style="margin-left: 10px;width:200px" placeholder="请选择门店">
            <el-option v-for="item in storeList" :label="item.basename"
              :value="item.base" :key="item.base">
              <span style="float: left">{{ item.basename }}</span>
            </el-option>
          </el-select>
          <el-button style="margin-left: 10px"  @click="reset">重置</el-button>
          <el-button type="warning" @click="exportExcel" style="margin-left: 10px;">导出至excel</el-button>
        </el-col>
      </el-row>
      <el-table
        border
        v-loading="loading"
        :data="materialOutData"
        style="margin-top: 10px;">
        <el-table-column label="出仓日期" prop="insert_time" min-width="110" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ new Date(scope.row.insert_time).toLocaleDateString().split('/').join('-') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="sell_number" width="130" align="center" fixed="left"></el-table-column>
        <el-table-column label="分类" prop="category" min-width="130" align="center" fixed="left"></el-table-column>
        <el-table-column label="商品名称" prop="name" min-width="160" align="center" fixed="left"></el-table-column>
        <el-table-column label="采购日期/加工日期" prop="sale_time" min-width="130" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ new Date(scope.row.sale_time).toLocaleDateString().split('/').join('-') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" width="80" align="center"></el-table-column>
        <el-table-column label="数量" prop="count" width="90" align="center"></el-table-column>
        <el-table-column label="成本" prop="price" min-width="100" align="center" v-if="groupid === 0 || groupid === 2">
          <template slot-scope="scope">
            <span>{{ parseFloat(scope.row.price).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总成本" min-width="120" align="center" v-if="groupid === 0 || groupid === 2">
          <template slot-scope="scope">
            <span>{{ parseFloat(scope.row.price * scope.row.count).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="65" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.type === 1 ? '加工' : '售出' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售价" prop="sell_price" min-width="100" align="center" v-if="groupid === 0 || groupid === 2">
          <template slot-scope="scope">
            <span>{{ parseFloat(scope.row.sell_price).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总售价" min-width="120" align="center" v-if="groupid === 0 || groupid === 2">
          <template slot-scope="scope">
            <span>{{ parseFloat(scope.row.sell_price * scope.row.count).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="流向" prop="base_name" width="100" align="center"></el-table-column>
        <el-table-column label="备注" prop="comment" min-width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="deleteHouseOut(scope.row.id, scope.row.type)" v-if="scope.row.type === 2">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pager.currPage"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.totalCount">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      groupid: '',
      loading: false,
      pager: {
        currPage: 1,
        pageSize: 10,
        totalCount: 0
      },
      materialOutData: [],
      exportSearch: {
        exportTime: '',
        endTime: '',
        base: ''
      },
      storeList: []
    }
  },
  mounted() {
    this.getUserInfo()
    this.getStoreList()
    this.getHouseOutList()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const { data: result } = await this.$http.get('/user/' + localStorage.userid)
      if (result.status !== 200) return this.$message.error(result.msg)
      this.groupid = result.data.groupid * 1
    },
    // 获取门店
    async getStoreList() {
      const { data: result } = await this.$http.get('/store/all')
      if (result.status !== 200) return this.$message.error(result.msg)
      this.storeList = result.data
    },
    async getHouseOutList() {
      this.loading = true
      const params = {
        page: this.pager.currPage,
        pageSize: this.pager.pageSize,
        process: 0
      }
      const { data: result } = await this.$http.get('/house-out', { params: params })
      if (result.status !== 200) {
        this.loading = false
        this.materialOutData = '暂无数据'
        return this.$message.error(result.msg)
      }
      this.loading = false
      this.materialOutData = result.data
      this.pager = result.pager
    },
    // 删除信息
    async deleteHouseOut(id, type) {
      const params = {
        id: id,
        type: type
      }
      const { data: result } = await this.$http.get('/house-out/delete', { params: params })
      if (result.status !== 200) return this.$message.error(result.msg)
      this.pager.currPage = 1
      this.getHouseOutList()
      this.$message.success('删除成功')
    },
    handleSizeChange(pageSize) {
      this.pager.pageSize = pageSize
      this.getHouseOutList()
    },
    handleCurrentChange(currentPage) {
      this.pager.currPage = currentPage
      this.getHouseOutList()
    },
    reset() {
      this.exportSearch = {
        exportTime: '',
        base: ''
      }
    },
    // 导出
    async exportExcel() {
      this.loading = true
      var data = {
        process: 0,
        groupid: this.groupid
      }
      if (this.exportSearch.exportTime) {
        const startTime = new Date(this.exportSearch.exportTime[0])
        const syear = startTime.getFullYear() // 获取当前年份
        const smonth = startTime.getMonth() + 1 // 获取当前月份(0-11,0代表1月所以要加1);
        const sday = startTime.getDate() // 获取当前日（1-31）
        const endTime = new Date(this.exportSearch.exportTime[1])
        const eyear = endTime.getFullYear() // 获取当前年份
        const emonth = endTime.getMonth() + 1 // 获取当前月份(0-11,0代表1月所以要加1);
        const eday = endTime.getDate() // 获取当前日（1-31）
        if (startTime) {
          data.startTime = `${syear}-${smonth}-${sday}`
        }
        if (endTime) {
          data.endTime = `${eyear}-${emonth}-${eday}`
        }
      }
      if (this.exportSearch.base !== '') {
        data.base = this.exportSearch.base
      }
      await this.$http.post('/house-out/export', data, { type: 'json',responseType:'blob' }).then(res => {
        if (res.status === 200) {
          const blob = res.data
          const reader = new FileReader()
          reader.readAsDataURL(blob)
          reader.onload = (e) => {
            const a = document.createElement('a')
            a.download = '原料出库明细.xlsx'
            a.href = e.target.result
            a.click()
          }
          this.loading = false
          return this.$message.success('导出成功')
        }
        this.loading = false
        return this.$message.error(res.msg)
      }).catch (() => {
        this.loading = false
        return this.$message.error('导出失败')
      })
    },
  }
}
</script>